package com.jiaxiaobang.majiang.majiang.job;

import com.jiaxiaobang.majiang.majiang.entity.EquipmentStatus;
import com.jiaxiaobang.majiang.majiang.entity.QsgDevice;
import com.jiaxiaobang.majiang.majiang.repository.EquipmentStatusRepository;
import com.jiaxiaobang.majiang.majiang.repository.QsgDeviceRepository;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.domain.Example;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

@Configuration
@EnableScheduling
@Slf4j
public class TaskStatusJob {

    @Autowired
    private EquipmentStatusRepository equipmentStatusRepository;

    @Autowired
    private QsgDeviceRepository qsgDeviceRepository;

    /**
     * @Scheduled-cron : 指定定时任务的执行时间
     * 或直接指定时间间隔，例如：10秒
     * @Scheduled(fixedRate=5000)
     */
    @Scheduled(cron = "0/10 * * * * ?")
    private void updateTaskStatus() {
        log.info("执行静态定时任务时间: {}", LocalDateTime.now());
        EquipmentStatus statusInfo = new EquipmentStatus();
        Example<EquipmentStatus> example = Example.of(statusInfo);
        List<EquipmentStatus> equipments = equipmentStatusRepository.findAll(example);
        for (EquipmentStatus equip: equipments
             ) {
            Date lastUpdateTime = equip.getUpdateTime();
            Date current = new Date();
            if((current.getTime() - lastUpdateTime.getTime()) >= 60000){
                equip.setStatus(1);
                equipmentStatusRepository.save(equip);
                //更新设备状态
                QsgDevice param = new QsgDevice();
                param.setDeviceCode(equip.getEquipmentId());
                Example<QsgDevice> deviceParam = Example.of(param);
                List<QsgDevice> devices = qsgDeviceRepository.findAll(deviceParam);
                if(null != devices && !devices.isEmpty()){
                    QsgDevice currentDevice = devices.get(0);
                    currentDevice.setOlStatus(1);
                    qsgDeviceRepository.save(currentDevice);
                }
            }else{
                equip.setStatus(0);
                equipmentStatusRepository.save(equip);
                //更新设备状态
                QsgDevice param = new QsgDevice();
                param.setDeviceCode(equip.getEquipmentId());
                Example<QsgDevice> deviceParam = Example.of(param);
                List<QsgDevice> devices = qsgDeviceRepository.findAll(deviceParam);
                if(null != devices && !devices.isEmpty()){
                    QsgDevice currentDevice = devices.get(0);
                    currentDevice.setOlStatus(0);
                    qsgDeviceRepository.save(currentDevice);
                }
            }
        }
    }
}
